(function () {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:loginDialog
     * @description
     * # loginDialog
     */
    angular.module('webApp')
        .run(["$templateCache", "dataService",
            function ($templateCache, dataService) {
                var tplName = "views/directives.logindialog.client.html";
                dataService.tpl(tplName).then(function (html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('loginDialog', ["$rootScope", "helper", function ($rootScope, helper) {
            return {
                restrict: 'EA',
                template: "<span></span>",
                scope: {},
                controller: ['$scope', 'authService', 'sessionService', 'dataService', '$compile', 'helper', '$templateCache', '$state', 'ERP_CONFIG', '$location', 'cacheService', function ($scope, authService, sessionService, dataService, $compile, helper, $templateCache, $state, ERP_CONFIG, $location, cacheService) {
                    $scope.user_name = null;
                    $scope.password = null;
                    $scope.userType = 1;
                    $scope.cleanCache = function ($event) {
                        dataService.removeAllCache();
                        helper.myTip("success", null, null, null, null, null, "success");
                    }

                    this.closeWin = function () {
                        // loadingToggle(true);
                        if ($scope.loginWin) {
                            $scope.loginWin.modal("hide");
                        }
                    }

                    function GetQueryString(name) {
                        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                        var r = window.location.search.substr(1).match(reg);
                        if (r != null) return unescape(r[2]);
                        return null;
                    }
                    $scope.wxcodeput = function () {
                        dataService.wxaccess_token({ code: $scope.code }).then(function (result) {
                            if (result.Msg) {
                                var location_url = ERP_CONFIG.eprUrl + "/web/dhfshop/app/shop.html#" + $location.url();
                                location_url = encodeURIComponent(location_url);
                                window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ERP_CONFIG.BackGzhId + "&redirect_uri=" + location_url + "&response_type=code&scope=snsapi_userinfo#wechat_redirect"
                            } else {
                                // sessionService.put("token",result.token);
                                cacheService.set("token", result.token);
                                $rootScope.getUserInfo(true);
                            }
                        })
                    }
                    $scope.registerclick = function () {
                        $scope.shoploginWin.close();
                        $state.go("login.register");
                    }
                    var dialog = null;
                    $scope.shoploginWin = new auiDialog();
                    this.showLogin = function () {
                        $scope.code = GetQueryString("code");
                        // console.log($location.search().code);
                        // loadingToggle(false);
                        $scope.error = null;
                        //弹出
                        if ($rootScope.is_weixin() && (!cacheService.get('token'))) {
                            var location_url = ERP_CONFIG.eprUrl + "/web/dhfshop/app/shop.html#" + $location.url();
                            // return false;
                            location_url = encodeURIComponent(location_url);
                            console.log(cacheService.get('token'));
                            // return false;
                            if ($scope.code && (!cacheService.get('token'))) {
                                $scope.wxcodeput();
                            } else if ($scope.code == undefined) {
                                window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ERP_CONFIG.BackGzhId + "&redirect_uri=" + location_url + "&response_type=code&scope=snsapi_userinfo#wechat_redirect"
                            }
                        } else if (!$rootScope.is_weixin()) {
                            var loginhtml = $templateCache.get("views/directives.logindialog.client.html");

                            console.log("22", $scope.shoploginWin.isShow, $('div.aui-content'), $('div.aui-content'));
                            $scope.shoploginWin.alert({
                                title: "登录",
                                msg: loginhtml,
                                buttons: ['登录'],
                            }, function (ret) {
                                if (!($scope.user_name && $scope.password)) {
                                    alert("error: name && password must be set");
                                    return false;
                                }
                                dataService.login($scope.user_name, $scope.password).then(function (data) {
                                    if (data.token) {
                                        //写入本地缓存
                                        cacheService.set("token", data.token)
                                        // sessionService.put("token", data.token);
                                        authService.loginConfirmed('success', function (config) {
                                            //自动追加token
                                            config.data["token"] = data.token;
                                            return config;
                                        });
                                        // _this.close();
                                        // loadingToggle(true);

                                    } else {
                                        $scope.error = data.Msg;
                                    }
                                });
                            });
                            $compile($('div.aui-content'))($scope);
                        }
                    }
                }],
                link: function (scope, elem, attrs, ctr) {
                    scope.$on('event:auth-shoploginRequired', function () {
                        ctr.showLogin();
                    });
                    scope.$on('event:auth-loginConfirmed', function () {

                    });
                    scope.$on('event:close_login_win', function () {
                        ctr.closeWin();
                    });
                    //通知完成加载
                    $rootScope.$broadcast("event:login-dialog-init-done");
                }
            }
        }]);
})();
